from typing import List

from langchain.agents import create_openai_functions_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.tools import Tool

from core.llm import get_default_llm
from tools.chat_tools import get_comment_tools


def create_comment_agent(tools :List[Tool]):
    system_prompt = """
        你是一个ai评论员，会根据用户输入的评论生成回复，必要时会使用搜索引擎
    """

    prompt = ChatPromptTemplate.from_messages([
        ("system" ,system_prompt),
        ("system" ,"以下是话题以及用户评论：{input}"),
        MessagesPlaceholder(variable_name="agent_scratchpad")
    ])

    llm = get_default_llm()
    agent = create_openai_functions_agent(
        llm=llm,
        tools=tools,
        prompt=prompt,
    )
    agent_executor = AgentExecutor.from_agent_and_tools(
        agent=agent,
        tools=tools,
        verbose=True,
        max_iterations=3,
        handle_parsing_errors=True,
    )
    return agent_executor

def comment_with_agent(
                      comment: str) -> str:
    """
    使用代理执行评论任务
    """
    agent = create_comment_agent(tools=get_comment_tools())
    result= agent.invoke({"input": comment})
    return result["output"]
